#!/bin/bash

SKIP=1350;
systemctl stop armbian-resize-filesystem.service
systemctl disable armbian-resize-filesystem.service


DEV_EMMC="/dev/mmcblk1"
DEV_EMMC2="/dev/mmcblk1"
echo $DEV_EMMC

# 判断内核版本是否 >= 5.10
KERNEL_VERSION=$(uname -r)
K_VER=$(echo "$KERNEL_VERSION" | cut -d '.' -f1)
K_MAJ=$(echo "$KERNEL_VERSION" | cut -d '.' -f2)

if [ $K_VER -eq 5 ];then
	if [ $K_MAJ -ge 10 ];then
		K510=1
	else
		K510=0
	fi
elif [ $K_VER -gt 5 ];then
	K510=1
else
	K510=0
fi

echo "Start backup u-boot default"
dd if="${DEV_EMMC2}" of=/root/u-boot-default-aml.img bs=1M count=4 conv=fsync
exists_pts=$(parted ${DEV_EMMC} print |grep 'primary'|wc -l)
if [ $exists_pts -gt 0 ];then
    i=1
    while [ $i -le $exists_pts ]
    do
        parted -s ${DEV_EMMC} rm $i 2>/dev/null
        let i=i+1
    done
fi
dd if=/dev/zero of=${DEV_EMMC} bs=512 count=1 conv=fsync

echo "Start create MBR and partittion"
parted -s "${DEV_EMMC}" mklabel msdos 2>/dev/null
parted -s "${DEV_EMMC}" mkpart primary fat32 $((SKIP*1024*1024))b 100% 2>/dev/null


echo "Start restore u-boot"
dd if=/root/u-boot-default-aml.img of="${DEV_EMMC}" conv=fsync bs=1 count=442 
dd if=/root/u-boot-default-aml.img of="${DEV_EMMC}" conv=fsync bs=512 skip=1 seek=1
PART_BOOT="${DEV_EMMC}p1"
mkfs.vfat -n "BOOT_EMMC" $PART_BOOT
sync
echo "Done"

echo "Start copy system for eMMC."

